package com.lx.Login.web;

import com.lx.Login.bean.LoginPropertise;
import com.lx.Login.service.MailBiz;
import com.lx.bean.Result;
import com.lx.biz.BizException;
import com.lx.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("login")
public class LoginDo {

    @Autowired
    LoginPropertise loginPropertise;

    @GetMapping("config")
    public LoginPropertise loginPropertose(){
        return loginPropertise;
    }


    @Autowired
    JdbcTemplate jdbcTemplate;

    @RequestMapping("login")
    public Result login(String username, String password, HttpSession session) throws BizException {
        Utils.checkEmpty(username, "请输入用户名!");
        Utils.checkEmpty(password, "请输入密码！");
        Utils.check(password.trim().length() < 3, "密码不能少于三个字符");
        System.out.println("username = " + username);
        System.out.println("password = " + password);
        String sql = "select * from %s where %s=? and %s=?";
        sql = String.format(sql, loginPropertise.getUserTable(),
                loginPropertise.getUsernameColumn(),
                loginPropertise.getPasswordColumn());
        System.out.println("sql = " + sql);
        List list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(loginPropertise.getUserClassObject()), username, password);
        Utils.check(list.isEmpty(), "用户名或密码错误");
        Utils.check(list.size() > 1, "数据库设计问题");
        Object user = list.get(0);
        session.setAttribute(loginPropertise.getSessionKey(), user);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("user", user);
        map.put("goto", session.getAttribute("goto"));
        return new Result(1, "登陆成功", map);
    }

    @RequestMapping("myinfo")
    public Result myinfo(HttpSession session) throws BizException {
        Object myinfo = session.getAttribute(loginPropertise.getSessionKey());
        if (myinfo == null) {
            throw new BizException("未登录");
        }
        return new Result(1, "已登录", myinfo);
    }

    @RequestMapping("logout")
    public ModelAndView logout(ModelAndView modelAndView, HttpSession session) throws BizException {
        session.invalidate();
        modelAndView.setViewName("redirect:/");
        return modelAndView;
    }

    @RequestMapping("getUsernameColumn")
    String getUsernameColumn(){
        return loginPropertise.getUsernameColumn();
    }

    @RequestMapping("reg")
    public Result reg(String username, String pwd, String repwd, String cname, String email, String image) throws BizException {
        Utils.checkEmpty(username, "请输入用户名!");
        Utils.checkEmpty(pwd, "请输入密码！");
        Utils.checkEmpty(repwd, "请确认密码！");
        Utils.check(pwd.trim().length() < 3, "密码不能少于三个字符");
        Utils.checkEmpty(cname,"请输入中文名");
        Utils.checkEmpty(email, "请输入邮箱");
        String sql1 = "select * from %s where %s=?";
        sql1 = String.format(sql1, loginPropertise.getUserTable(),
                                  loginPropertise.getUsernameColumn());

        List list = jdbcTemplate.query(sql1, new BeanPropertyRowMapper<>(loginPropertise.getUserClassObject()), username);
        if (!list.isEmpty()) {
            return new Result(0, "该用户名也被注册, 请重新输入用户名",null);
        }
        if (!pwd.equals(repwd)) {
            return new Result(0, "两次密码不一致, 请重新输入", null);
        }
        String sql2 = "insert into %s(id, ename, cname, password, email, headimg, createtime, status) values(?,?,?,?,?,?,?,?)";
        sql2 = String.format(sql2, loginPropertise.getUserTable());
        jdbcTemplate.update(sql2, null, username, cname, pwd, email, image, new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()), "用户");

        return new Result(1, "注册成功", null);
    }

    @Autowired
    MailBiz mailBiz;

    @RequestMapping("forgetPwd")
    public Result forgetPwd(String username, String email, HttpSession session){
        String sql1 = "select * from %s where %s=?";
        sql1 = String.format(sql1, loginPropertise.getUserTable(),
                loginPropertise.getUsernameColumn());
        List list = jdbcTemplate.query(sql1, new BeanPropertyRowMapper<>(loginPropertise.getUserClassObject()), username);
        if (list.isEmpty()) {
            return new Result(-1, "没有该用户账号", null);
        }
        String msg = "验证码为: ";
        // 时间挫
        String vcode = System.currentTimeMillis()+"";
        vcode = vcode.substring(vcode.length() - 4);
        msg += vcode;
        session.setAttribute("forgetVcode", vcode);
        session.setAttribute("forgetUser", list);
        mailBiz.sendSimpleMail("忘记密码的验证", "3261810649@qq.com", email, msg);
        // TODO 部分隐藏邮箱
        // TODO 验证码设置时效
        String prefix = email.substring(0, 3);
        String replace = email.replaceAll("[a-zA-Z0-9]+@", "******");
        String Email = prefix + replace;
        // TODO vcode的有效期 三分钟有效  定时任务 Task
        // java自带的java.util.Timer类 该类允许你调用一个java.util.TimerTask任务
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                session.removeAttribute("forgetVcode");
            }
        };
        // task-所安排的任务  time-执行任务的时间 在时间等于或者超过time的时候执行且仅执行一次
        Timer timer = new Timer();
        timer.schedule(task, 18000); //180s

        return new Result(1, "验证码已经发送到你的"+Email+"邮箱, 验证码在三分钟后过期", null);
    }


}
